import { Inject, Middleware, Config } from "@midwayjs/core";
import { Context, NextFunction } from "@midwayjs/koa";
import { JwtService } from "@midwayjs/jwt";
import { Utils } from "../utils";

@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService;

  public static getName(): string {
    return "jwt";
  }

  @Config("wapis")
  private wapis: Array<string>;

  @Config()
  private jwtCookieKey: string;

  @Inject()
  utils: Utils;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (ctx.path === "/") {
        ctx.redirect("/index.html");
      } else if (this.isWapi(ctx)) {
        await next();
      } else {
        const token = ctx.cookies.get(this.jwtCookieKey);
        if (token) {
          try {
            const result = await this.jwtService.verify(token, {
              complete: true
            });
            if (result) {
              await next();
            } else {
              this.utils.response.unauthorize(ctx);
            }
          } catch (error) {
            console.log(error);
            this.utils.response.fail(error);
          }
        } else {
          this.utils.response.unauthorize(ctx);
        }
      }
    };
  }

  // 配置忽略鉴权的路由地址
  public isWapi(ctx: Context): boolean {
    const index = this.wapis.findIndex((d) => ctx.path.indexOf(d) >= 0);
    return index >= 0;
  }
}
